package com.it.xuehang.handler;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;

public class AutoDateConverter {

    // 定义可能的日期格式列表
    private static final List<String> DATE_FORMATS = Arrays.asList(
            "yyyyMMdd",
            "yyyy-MM-dd",
            "dd/MM/yyyy",
            "MM/dd/yyyy",
            "yyyy.MM.dd",
            "dd.MM.yyyy",
            "yyyy-MM-dd"

    );

    public static LocalDate convertToDate(String dateString) throws DateTimeParseException {
        for (String format : DATE_FORMATS) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
                return LocalDate.parse(dateString, formatter);
            } catch (DateTimeParseException e) {
                // 如果当前格式不匹配，继续尝试下一个格式
                continue;
            }
        }
        // 如果所有格式都不匹配，则抛出异常
        throw new DateTimeParseException("无法识别的日期格式: " + dateString, dateString, 0);
    }

    public static void main(String[] args) {
        String inputDate = "20241217";
        try {
            LocalDate date = convertToDate(inputDate);
            System.out.println("转换后的日期: " + date);
        } catch (DateTimeParseException e) {
            System.out.println(e.getMessage());
        }
    }
}
